package org.emergency.framework.serviceImpl.oa;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.emergency.framework.common.IdsService;
import org.emergency.framework.constant.IDConstant;
import org.emergency.framework.dao.IUtilDao;
import org.emergency.framework.dao.oa.ITbRoleDAO;
import org.emergency.framework.model.TbRole;
import org.emergency.framework.service.oa.ITbRoleService;
import org.springframework.stereotype.Service;

@Service("roleServiceImpl")
public class TbRoleServiceImpl implements ITbRoleService {

	@Resource(name = "tbRoleDAO")
	private ITbRoleDAO iTbRoleDAO;

	@Resource(name = "idsServiceImpl")
	private IdsService idsService;

	@Resource(name = "utilDao")
	private IUtilDao utilDao;

	public List<TbRole> findAll() {
		String hqlString = "from TbRole t where t.isEnabled is true";
		return iTbRoleDAO.queryListByHql(hqlString);
	}

	public boolean save(TbRole tbRole) {
		System.out.println("*******");
		String tbRoleId = null;
		tbRoleId = idsService.findTablePK(IDConstant.TB_ROLE);
		tbRole.setTbRoleId(tbRoleId);
		tbRole.setEnabled(true);
		
		System.out.println(tbRole.getName()+","+tbRole.getTbRoleId()+"**");
			iTbRoleDAO.save(tbRole);
		return true;
	}

	public boolean delete(TbRole tbRole) {
		String hqlString = null;
		//删除中间表
		hqlString = "delete TbRolePermission t where t.tbRole.tbRoleId = '"
				+ tbRole.getTbRoleId() + "' ";
			iTbRoleDAO.executeDelOrUpdateHql(hqlString);
			
			//删除中间表
			hqlString = "delete TbUserRoleEntity t where t.tbRole.tbRoleId = '"
				+ tbRole.getTbRoleId() + "' ";
			iTbRoleDAO.executeDelOrUpdateHql(hqlString);
			
			hqlString = "delete TbRole t where t.tbRoleId = '"+tbRole.getTbRoleId()+"'";
			iTbRoleDAO.executeDelOrUpdateHql(hqlString);
			
		return true;
	}

	public void updateRole(TbRole tbRole) {
		String hqlString = "update TbRole t set ";
		if (!((tbRole.getName() == null))) { // 名字不为空的话，就更新下名字
			hqlString += "t.name='" + tbRole.getName() + "',";
		}
		hqlString = hqlString.substring(0, hqlString.length() - 1);// 把逗号去掉
		hqlString += " where t.tbRoleId=" + tbRole.getTbRoleId();

		utilDao.updatebyHQL(hqlString);
	}

}
